<template>
<div class="single-file-select-cp">
    <div 
        class="bt"
        @click="onClick">
        <template>
            {{title || '选择文件'}}
        </template>
    </div>
    <input
        ref="input" 
        type="file" 
        name="file"
        :accept="accept"
        @change="onChange"/>
</div>
</template>

<script>
//单个文件选择组件
export default {
    props:{
        title:{
            type:String,
            default:'',
        },
        accept:{  //需要的是js 扩展名 MIME 描述
            type:String,
            default:'',
        },
    },
    methods: {
        onClick(){  //选择文件
            this.$refs.input.value = '';  //清空选择的文件
            this.$refs.input.click();
        },
        onChange(e) {
            const [ file ] = e.target.files || e.dataTransfer.files;
            const type = file.type;
            if(!this.accept){
                this.$emit('onChange', file);
                return;
            }
            if(this.accept.indexOf(type) !== -1){
                this.$emit('onChange', file);
            }else{
                this.$message.error('文件类型错误，只允许格式：'+this.accept);
            }
        },
    },
}
</script>

<style scoped lang="scss">
.single-file-select-cp{
    position: relative;
    width: 100%;
    height: 100%;
    .bt {
        width: 100%;
        height: 100%;
        padding: 5px 10px;
        color: #1e3c6a;
        background-color: #1dc979;
        font-size: 15px;
        text-align: center;
        font-weight: bold;
        box-sizing: border-box;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    input{
        position: absolute;
        display:none;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
    input[type=file]::-webkit-file-upload-button { 
        width: 0;
        padding: 0;
        margin: 0;
        -webkit-appearance: none;
        border: none;
    }
}
</style>
